package com.jiufengxinxi.ts.device.equipment.printer;


import com.jiufengxinxi.ts.common.utils.HexUtil;
import com.jiufengxinxi.ts.common.utils.printer.ConnectUsbEqu;
import com.jiufengxinxi.ts.common.utils.socket.ISocketRequestHandle;
import com.jiufengxinxi.ts.common.utils.socket.client.MultiThreadClient;
import com.jiufengxinxi.ts.device.callback.IDeviceStateCallback;
import com.jiufengxinxi.ts.device.interfaces.ICommDevice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;

public abstract class IPrinterDevice extends ICommDevice implements ISocketRequestHandle {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private ConnectUsbEqu connectUsbEqu;

    private MultiThreadClient client;

    private short pid = 0;
    private short vid = 0;

    public IPrinterDevice(short pid,short vid) {
        super(null);
        this.pid = pid;
        this.vid = vid;
        connectionUSB();
    }

    public IPrinterDevice(String host,int port){
        super(null);
        client = new MultiThreadClient(host,port);
        client.setCharacterSet("GBK");
        client.setSocketRequestHandle(this);
    }

    public void connectionUSB(){
        if(isUsb()&&(connectUsbEqu==null||!connectUsbEqu.isOpen())) {
            connectUsbEqu = new ConnectUsbEqu(pid, vid);
        }
    }

    public void disconnectionUSB(){
        if(connectUsbEqu!=null){
            connectUsbEqu.disconnection();
        }
    }

    public boolean isUsb(){
        return pid!=0&&vid!=0;
    }

    public IPrinterDevice(String port) {
        super(port.split(":")[0]);
        setCoded("GBK");
        if(port.split(":").length>1){
            setBaudrate(Integer.parseInt(port.split(":")[1]));
        }else {
            setBaudrate(9600);
        }
        setReciveBytes(true);
        initDevide("");
        //startup();
        logger.info("============串口打印机初始化："+port);
    }

    @Override
    public void produceSinal(String sinal) {
        //System.out.println("打印机返回    :     "+sinal);
    }

    @Override
    public void produceSinal(byte[] sinal) {
        System.out.println("打印机返回    :     "+ HexUtil.hexString2binaryString(HexUtil.bytesToHexString(sinal).substring(0,2)));
    }

    @Override
    public void initDevide(String... param) {
        super.initDevide(param);
    }

    @Override
    public String status() {
        return super.status();
    }

    @Override
    public boolean check() {
        return super.check();
    }

    @Override
    public void destroy() {
        try{
            close();
        }catch (Exception e){
        }

        try{
            connectUsbEqu.disconnection();
        }catch (Exception e){
        }

        try{
            client.disconnect();
        }catch (Exception e){
        }
    }

    @Override
    public String getDeviceName() {
        return "MS_NP80A";
    }

    @Override
    public boolean decodeRelation(String report) {
        return false;
    }

    @Override
    public void connection(String from) {

    }

    @Override
    public String disconnection(String from) {
        return null;
    }

    @Override
    public void setDeviceCallback(IDeviceStateCallback deviceCallback) {
        //super.setDeviceCallback();
    }


    public void print(String text){

        System.out.println("打印: "+text);
        connectionUSB();

        if(Character.isDigit(text.charAt(0))){
            int num = Integer.parseInt(text.substring(0,1));
            text = text.substring(1);
            for(int i=0;i<num;i++){
                excutePrint(text);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else{
            excutePrint(text);
        }

        if(client!=null){
            try {
                Thread.sleep(500);
                client.disconnect();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        disconnectionUSB();
    }


    protected abstract void excutePrint(String text);


    @Override
    public void write(byte[] message) {
        if(connectUsbEqu!=null){
            try {
                connectUsbEqu.sendMassge(message);
            } catch (UsbDisconnectedException e) {
                logger.error("USB已经断开，准备重连",e);
                try {
                    Thread.sleep(500);
                    connectUsbEqu.useUsb();
                    write(message);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }catch (UsbException e){
                logger.error(e.getMessage(),e);
            }
        }else if(client!=null){
            client.send(message);
        }else{
            super.write(message);
        }
    }

    /*public void write(String message) {
        if(connectUsbEqu==null){
            super.write(message);
        }else{
            try {
                connectUsbEqu.sendMassge(message);
            } catch (UsbDisconnectedException e) {
                logger.error(e.getMessage(),e);
            }catch (UsbException e){
                logger.error(e.getMessage(),e);
            }
        }
    }*/

    public ConnectUsbEqu getConnectUsbEqu() {
        return connectUsbEqu;
    }

    public void setConnectUsbEqu(ConnectUsbEqu connectUsbEqu) {
        this.connectUsbEqu = connectUsbEqu;
    }

    public short getPid() {
        return pid;
    }

    public void setPid(short pid) {
        this.pid = pid;
    }

    public short getVid() {
        return vid;
    }

    public void setVid(short vid) {
        this.vid = vid;
    }
}
